package net.lcheng.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.lcheng.commons.utils.PageList;
import net.lcheng.commons.utils.ParseMD5;
import net.lcheng.dao.SysRolesMapper;
import net.lcheng.dao.SysUserRolesMapper;
import net.lcheng.dao.SysUsersMapper;
import net.lcheng.model.*;
import net.lcheng.service.SysUsersService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * Created by qiliping on 15/11/10.
 */
@Service("sysUsersService")
public class SysUsersServiceImpl implements SysUsersService {

    @Resource
    private SysUsersMapper mapper;

    @Resource
    private SysUserRolesMapper userRoleMapper;

    @Resource
    private SysRolesMapper rolesMapper;

    /***
     * 修改登录密码
     * @param id
     * @param pwd
     * @return
     */
    @Override
    public int changePassword(long id, String pwd) {
        SysUsers user = new SysUsers();
        user.setId(id);
        user.setPassword(pwd);
        return mapper.updateByPrimaryKeySelective(user);
    }

    /**
     * 根据用户名获取用户
     * */
    @Override
    public SysUsers getUserByUsername(String username) {
        SysUsersExample example = new SysUsersExample();
        example.or().andUsernameEqualTo(username);
        List<SysUsers>  users = mapper.selectByExample(example);
        if(users==null || users.size()==0) {
            return null;
        }else {
            return users.get(0);
        }
    }
    /**
     * 获取用户
     * @param userId
     * */
    @Override
    public SysUsers getUserByUserId(long userId) {
        return mapper.selectByPrimaryKey(userId);
    }

    /**
     * 删除用户
     * @param userId
     * */
    @Override
    public int deleteUser(long userId) {
        return mapper.deleteByPrimaryKey(userId);
    }

    /**
     * 获取用户List
     * */
    @Override
    public PageList<SysUsers> getUserList(int pageIndex, int pageSize, String name) {
        PageHelper.startPage(pageIndex,pageSize);
        SysUsersExample example = new SysUsersExample();
        if(!StringUtils.isEmpty(name)) {
            example.or().andTrueNameLike(name);
        }
        List<SysUsers> list = mapper.selectByExample(example);
        PageInfo<SysUsers> pageInfo = new PageInfo<>(list);

        PageList<SysUsers> pageList = new PageList<>();
        pageList.list = pageInfo.getList();
        pageList.totalCount = pageInfo.getTotal();
        pageList.totalPage=pageInfo.getPages();
        pageList.pageIndex=pageInfo.getPageNum();
        pageList.pageSize=pageInfo.getPageSize();

        return pageList;
    }

    /**
     * 新增用户
     * @param userName
     * @param password
     * */
    @Override
    public int addUser(String userName,String password,String email,String trueName,String jobNo,String department,String phone,Integer[] roleIds) {
        //添加用户
        SysUsers user =  new SysUsers();
        user.setCreateOn(new Date());
        user.setDepartment(department);
        user.setEmail(email);
        user.setIsAdministrator(0);
        user.setJobNo(jobNo);
        user.setPassword(ParseMD5.parseStrToMd5L32(password));
        user.setPhone(phone);
        user.setStatus(1);
        user.setTrueName(trueName);
        user.setUsername(userName);
        user.setPasswordSalt("");
        mapper.insert(user);
        //查询UserId
        SysUsers newUser = this.getUserByUsername(userName);

        //添加用户角色
        for (Integer roleId:roleIds) {
            SysRoles roles = rolesMapper.selectByPrimaryKey(roleId);
            if (roles != null) {
                SysUserRoles userRole = new SysUserRoles();
                userRole.setUsername(userName);
                userRole.setUserId(newUser.getId().intValue());
                userRole.setRoleId(roleId);
                userRole.setRoleKey(roles.getRoleKey());
                userRole.setRoleName(roles.getRoleName());
                userRoleMapper.insert(userRole);
            }
        }

        return 1;
    }

    /**
     * 修改用户
     * @param userId
     * @param password
     * */
    @Override
    public int editUser(long userId,String password, String email, String trueName, String jobNo, String department, String phone, Integer[] roleIds) {
        SysUsers sysUsers =  mapper.selectByPrimaryKey(userId);
        if(sysUsers==null) return -1;

        //修改用户
        SysUsers user =  new SysUsers();
        user.setDepartment(department);
        user.setEmail(email);
        user.setJobNo(jobNo);
        user.setPhone(phone);
        user.setTrueName(trueName);
        user.setId(userId);
        if(!StringUtils.isEmpty(password)){
            user.setPassword(ParseMD5.parseStrToMd5L32(password));
        }
        mapper.updateByPrimaryKeySelective(user);

        //删除角色
        SysUserRolesExample rolesExample = new SysUserRolesExample();
        rolesExample.or().andUserIdEqualTo((int)userId);
        userRoleMapper.deleteByExample(rolesExample);

        //添加新角色
        for (Integer roleId:roleIds) {
            SysRoles roles = rolesMapper.selectByPrimaryKey(roleId);
            if(roles!=null) {
                SysUserRoles userRole = new SysUserRoles();
                userRole.setUsername(sysUsers.getUsername());
                userRole.setUserId((int) userId);
                userRole.setRoleId(roleId);
                userRole.setRoleKey(roles.getRoleKey());
                userRole.setRoleName(roles.getRoleName());
                userRoleMapper.insert(userRole);
            }
        }
        return 1;
    }
}
